﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.CrmContacto.Code;
using Web.Framework.Translate;
using Web.Framework;
using CrmContacto.Contracts.Contracts;
using CrmContacto.Contracts.Contracts.Search;
using CrmContacto.WebApp.Code.InnerClasses;
using CrmContacto.Contracts.Enums;
using CrmContacto.Contracts;
using Web.CrmContacto.Code.Security;
using Web.Framework.Helpers;

namespace CrmContacto.WebApp.App
{
    public partial class AccionesDeMarketingList : BasePage
    {
        private int? planMarketingId
        {
            get
            {
                return (int?)ViewState["planMarketingId"];
            }
            set
            {
                ViewState["planMarketingId"] = value;
            }
        }

        private List<LinkButton> actionButtons = new List<LinkButton>();
        LinkButton seleccionarListasButton = new LinkButton();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);                      
            
            seleccionarListasButton.ID = "BoAccionDeMktgMenuAgregarAccionAAccion";

            if (base.NavigationContext.AgregandoAccionesDeMarketingAAccionDeMarketing)
            {
                seleccionarListasButton.Text = LocalizationProvider.Instance["Bo.AccionDeMarketing.ActionMenu.AgregarAccionRelacionadaAAccionDeMarketing"];
            }           

            seleccionarListasButton.Click += new EventHandler(seleccionarListasButton_Click);
            actionButtons.Add(seleccionarListasButton);
            seleccionarListasButton.Visible = base.NavigationContext != null && (base.NavigationContext.AgregandoAccionesDeMarketingAAccionDeMarketing);

            base.LoadContextActions(actionButtons);
        }

        private void seleccionarListasButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (base.NavigationContext.AgregandoAccionesDeMarketingAAccionDeMarketing)
                {
                    List<int> listasIds = GetCheckedItemsId();

                    if (base.NavigationContext.AccionDeMarketingId.HasValue)
                    {
                        WebServiceHelper.AddAccionDeMarketingRelacionadaAAccionDeMarketing(base.NavigationContext.AccionDeMarketingId.Value, listasIds);

                        string urlToGoBack = base.NavigationContext.UrlToGoBack;
                        base.NavigationContext.UrlToGoBack = string.Empty;
                        //Volver();
                        Response.Redirect(urlToGoBack + string.Format("?Id={0}&addingAccionRelacionadaOk=1", base.NavigationContext.AccionDeMarketingId.Value), true);
                    }
                }                
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void Volver()
        {
            if (base.NavigationContext != null && !String.IsNullOrEmpty(base.NavigationContext.UrlToGoBack))
            {
                Response.Redirect(base.NavigationContext.UrlToGoBack, true);
            }
        }        

        private void SetThisPageToGoBack()
        {
            this.NavigationContext.UrlToGoBack = Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlAccionDeMarketingList;
        }

        protected override void OnPreLoad(EventArgs e)
        {
            base.OnPreLoad(e);
            if (!base.NavigationContext.AgregandoAccionesDeMarketingAAccionDeMarketing)
            {
                this.Grid.Columns[0].Visible = false;
            }
            else
            {
                this.Grid.Columns[2].Visible = false;                

                TitleNavContext.Visible = true;

                if (base.NavigationContext.AgregandoAccionesDeMarketingAAccionDeMarketing)
                    lblContexto.Text = LocalizationProvider.Instance["Bo.AccionesDeMktg.Context.AgregandoAccionesAAccionDeMarketing"];                
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                HasPermissionToSeeMe(CrmSecurity.MARKETINGACTION_SEARCH);

                this.lnkBuscar.Attributes.Add("aspnetid", this.lnkBuscar.ClientID);

                // Analizar si se esta usando para agregar en acciones de marketing, en donde hardcodeo el plan al q pertenece y los tipos válidos
                //?planDeMarketingId={0}&discriminadorId
                // HasPermissionToSeeMe(PlanProdSecurity.DESTINO_VER);
                if (!this.IsPostBack)
                {
                    if (!String.IsNullOrEmpty(this.Request.QueryString["planDeMarketingId"]))
                    {
                        planMarketingId = Convert.ToInt32(this.Request.QueryString["planDeMarketingId"]);
                    }

                    this.LoadCbos();

                    if (!String.IsNullOrEmpty(this.Request.QueryString["discriminadorId"]))
                    {
                        string discriminadorStr= this.Request.QueryString["discriminadorId"];
                        int discriminador = Convert.ToInt32(discriminadorStr);
                        
                        foreach (ListItem li in chkTipoAccion.Items)
                        {
                            if (li.Value == discriminadorStr)
                            {
                                li.Selected = true;
                            }
                        }
                        
                        this.chkTipoAccion.Enabled = false;
                        divTipoAccion.Attributes.Add("style", "display: none");
                        lblSearchResult.Text = string.Format(" - {0}", UIHelper.GetEnumDescription((DiscriminadorAccionDeMarketing)discriminador));
                    }

                    Buscar();
                }               
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void LoadCbos()
        {
            UIHelper.LoadEstados<DiscriminadorAccionDeMarketing>(this.chkTipoAccion, string.Empty);

            UIHelper.LoadEstados<EstadoPlanDeMarketing>(this.chkEstado, string.Empty);
        }

        protected override void ApplySecurity()
        {
            if (seleccionarListasButton.Visible)
            {
                seleccionarListasButton.Visible = HasPermissionFor(CrmSecurity.MARKETINGACTION_ADD_ACTION);
            }

            if (!base.NavigationContext.AgregandoAccionesDeMarketingAAccionDeMarketing)
            {
                this.Grid.Columns[2].Visible = HasPermissionFor(CrmSecurity.MARKETINGACTION_EDIT) || HasPermissionFor(CrmSecurity.MARKETINGACTION_SEARCH);                
            }           
        }

        private void Buscar()
        {
            AccionDeMarketingSearch search = new AccionDeMarketingSearch()
            {
                EmpresaId = BaseWebPage.CompanyId,
            };

            if (planMarketingId.HasValue)
            {
                search.PlanDeMarketingId = planMarketingId.Value;
            }

            search.NombreLike = this.txtNombre.Text;
            search.CodigoLike = this.txtCodigo.Text;
            search.FechaEventoDesde = UIHelper.GetDateTimeFromInputText(this.txtFechaDesde.Text);
            search.FechaEventoHasta = UIHelper.GetDateTimeFromInputText(this.txtFechaHasta.Text);
            search.DiscriminadorIdList = UIHelper.GetIntFromCheckBoxLst(this.chkTipoAccion);
            search.EstadoList = UIHelper.GetIntFromCheckBoxLst(this.chkEstado);

            List<AccionDeMarketing> accionesDeMarketingList = WebServiceHelper.GetAccionesDeMarketing(search);

            this.Grid.DataSource = accionesDeMarketingList;
            this.Grid.DataBind();

            pnlResults.Visible = true;
        }

        private List<int> GetCheckedItemsId()
        {
            List<int> selectedRowsIds = new List<int>();
            if (!String.IsNullOrEmpty(this.hidCheckedRows.Value))
            {
                string[] ids = this.hidCheckedRows.Value.Split('#');
                this.hidCheckedRows.Value = string.Empty;
                foreach (string id in ids)
                {
                    if (!String.IsNullOrEmpty(id))
                    {
                        int idInt = Convert.ToInt32(id);
                        if (!selectedRowsIds.Contains(idInt))
                        {
                            selectedRowsIds.Add(idInt);
                        }
                    }
                }
            }

            return selectedRowsIds;
        }

        protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    AccionDeMarketing accionDeMarketing = (AccionDeMarketing)e.Row.DataItem;

                    e.Row.Cells[2].Attributes.Add("title", "Editar");

                    if (!HasPermissionFor(CrmSecurity.MARKETINGPLAN_SEARCH))
                    {
                        LinkButton lnk = e.Row.Cells[4].FindControl("btnVerPlanMarketing") as LinkButton;
                        if (lnk != null)
                        {
                            lnk.OnClientClick = " return false; "; // Impide la navegación
                        }
                    }

                    //e.Row.Cells[3].Attributes.Add("title", "Eliminar");
                    //ImageButton btnEliminarCtrl = (ImageButton)e.Row.FindControl("btnEliminar");
                    //btnEliminarCtrl.OnClientClick = string.Format("return confirm('" + LocalizationProvider.Instance["Bo.Messages.ConfirmarEliminarRegistro"] + "')", accion.Nombre);                   
                    e.Row.Cells[8].Text = UIHelper.GetEnumDescription((DiscriminadorAccionDeMarketing)accionDeMarketing.Discriminador);
                    e.Row.Cells[9].Text = UIHelper.GetEnumDescription((EstadoPlanDeMarketing)accionDeMarketing.Estado);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Grid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "editar")
                {
                    int accionDeMarketingId = Convert.ToInt32(this.Grid.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    SetThisPageToGoBack();
                    this.Response.Redirect(string.Format(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlAccionDeMarketingSwap + "?Id={0}", accionDeMarketingId), true);
                }
                //else if (e.CommandName == "eliminar")
                //{
                //    int accionDeMarketingId = Convert.ToInt32(this.Grid.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                //    WebServiceHelper.EliminarAccionDeMarketing(accionDeMarketingId);
                //    Buscar();
                //}
                else if (e.CommandName == "verPlanMarketing")
                {
                    int accionDeMarketingId = Convert.ToInt32(this.Grid.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);

                    AccionDeMarketingSearch search = new AccionDeMarketingSearch();
                    search.Id = accionDeMarketingId;
                    AccionDeMarketing accionesDeMarketingToGoToPlan = WebServiceHelper.GetAccionesDeMarketing(search).First();
                    NavigationContext.RedirectTo(MiscClass.UrlPlanDeMarketingEdit, string.Format("?Id={0}", accionesDeMarketingToGoToPlan.PlanDeMarketingId));
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                this.Grid.PageIndex = e.NewPageIndex;

                Buscar();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkBuscar_Click(object sender, EventArgs e)
        {
            try
            {
                Buscar();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkExportarAExcel_Click(object sender, EventArgs e)
        {
            try
            {
                bool previousAllowPaging = this.Grid.AllowPaging;
                this.Grid.AllowPaging = false;

                Buscar();

                GridViewExportExcelUtil.Export("AccionesDeMarketing.xls", this.Grid, 0, 1, 2);

                this.Grid.AllowPaging = previousAllowPaging;
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}